import OSS from 'ali-oss'
import { getUploadCredentials } from '@/api/index.js'
import { nanoid } from 'nanoid'
import ImageBg from '@/assets/img/bg.jpg'
import ImageLogo from '@/assets/img/logo.png'
import ImageTitle from '@/assets/img/title.png'
import ImageSubTitle from '@/assets/img/sub-title.png'
import ImageText from '@/assets/img/apply/text.png'

export const uploadFile = async (file) => {
  const { data } = await getUploadCredentials()
  const client = new OSS({
    bucket: 'chunleibei',
    region: 'oss-cn-shanghai',
    accessKeyId: data.AccessKeyId,
    accessKeySecret: data.AccessKeySecret,
    stsToken: data.SecurityToken
  })
  const filename = nanoid() + '.' + file.name.split('.').pop()
  return client.put(filename, file)
}

export const createImage = (url) => {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.src = url
    img.onload = () => {
      resolve(img)
    }
    img.onerror = () => {
      reject(new Error('图片加载失败'))
    }
  })
}

export const drawPoster = async (userBase64, { company, name }) => {
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  canvas.width = 1242
  canvas.height = 2208
  const [bg, logo, title, subTitle, userImage, text] = await Promise.all([
    createImage(ImageBg),
    createImage(ImageLogo),
    createImage(ImageTitle),
    createImage(ImageSubTitle),
    createImage(userBase64),
    createImage(ImageText)
  ])

  ctx.drawImage(bg, 0, 0, canvas.width, canvas.height)
  ctx.drawImage(logo, 89, 56, 413, 112)
  ctx.drawImage(title, 61, 236, 1113, 399)
  ctx.drawImage(subTitle, 162, 633, 920, 133)

  const radius = 355
  ctx.save()
  ctx.beginPath()
  ctx.arc(621, 1298, radius, 0, 2 * Math.PI, false)
  ctx.clip()
  ctx.drawImage(userImage, 266, 943, 710, 710)
  ctx.restore()
  ctx.drawImage(text, 487, 1262, 730, 662)

  ctx.font = '60px Arial'
  ctx.fillStyle = '#fff'
  ctx.textAlign = 'center'
  ctx.fillText(company, canvas.width / 2, 1850)
  ctx.fillText(name, canvas.width / 2, 1930)

  return canvas
}

export const base64ToFile = (base64String, fileName, mimeType) => {
  const byteCharacters = atob(base64String.split(',').pop())
  const byteArrays = []

  for (let offset = 0; offset < byteCharacters.length; offset += 512) {
    const slice = byteCharacters.slice(offset, offset + 512)
    const byteNumbers = new Array(slice.length)
    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i)
    }
    const byteArray = new Uint8Array(byteNumbers)
    byteArrays.push(byteArray)
  }

  const blob = new Blob(byteArrays, { type: mimeType })
  return new File([blob], fileName, { type: mimeType })
}
